package com.zygh.coordinatestore.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lee
 *
 */
@Component
public class NormalUdpServerHandler extends ChannelInboundHandlerAdapter {


    private StatisticsServer statisticsServer;
    @Autowired
    private void setStatisticsServer(StatisticsServer statisticsServer){
        this.statisticsServer = statisticsServer;
    }
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ctx.channel().config().setWriteBufferHighWaterMark(1024*1024 * 8);
       if(!ctx.channel().isWritable()){
           System.out.println("-------------------------------------------------");
           System.out.println(ctx.channel().isWritable());
           System.out.println("-------------------------------------------------");
         }
        DatagramPacket packet = (DatagramPacket) msg;
        ByteBuf byteBuf = packet.copy().content();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        super.channelRead(ctx, msg);
        statisticsServer.doSave(bytes);
        //ReferenceCountUtil.release(msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
	}
}
